package com.hk.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hk.commons.DateUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.LongId;
import com.hk.commons.entity.Points;
import com.hk.commons.entity.PointsHistory;
import com.hk.commons.entity.sys.SysUser;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.IPointsHistory;
import com.hk.service.kyc.IPoints;
import com.hk.service.sys.ISysUser;


@Service
public class PointsHistoryImpl extends BaseServiceImpl<PointsHistory> implements IPointsHistory{

	private Logger logger = LoggerFactory.getLogger(PointsHistoryImpl.class);
	
	@Autowired 
	IPoints pointsService;
	
	@Autowired 
	ISysUser userService;
	
	
	@Override
	public Long add(PointsHistory model) {
		Long id = LongId.get();
		model.setId(id);
		model.setCts(System.currentTimeMillis());
		super.save(model);
		return id;
	}

	@Override
	public void delete(PointsHistory u) {
		delete(u);
	}

	@Override
	public void update(PointsHistory u) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public PointsHistory findById(long id) {
		 return getById(id);
	}
	
	@Override
	public Boolean add(long finUserId, Integer pointsId, String msg) {
		logger.info("PointsHistoryImpl will add new record info : finUserId = " + finUserId + 
				"  pointsId = " + pointsId + "  msg = " + msg);
		Points point = pointsService.findById(pointsId);
		SysUser finUser  = userService.findById(finUserId);
		
		if(point != null && finUser != null){
			PointsHistory pointsHistory = new PointsHistory();
			pointsHistory.setUserId(finUser.getId());
			pointsHistory.setPointsId(pointsId);
			pointsHistory.setScore(pointsService.getVal(pointsId));
			pointsHistory.setHistoryDesc(msg);
			Long id = this.add(pointsHistory);
			
			logger.info("PointsHistoryImpl add new record succ id = "+ id.toString());
		}else{
			logger.info("PointsHistoryImpl add new record failed pointId = " + pointsId 
					+ "  finUserId = " + finUserId);
		}
		
		 return  true;
	}

	@Override
	public Integer getDayTimes(Integer pointsId, Long userId) {
		Integer result = 0;
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);
		hqlFilter.addEQFilter("pointsId", pointsId);
		hqlFilter.addSql(" and cts > " + DateUtil.startOfTodDay() + " and cts < " + DateUtil.endOfTodDay());
		logger.info("hqlfilter is " + hqlFilter.getWhereAndOrderHql());
		Long times = countByFilter(hqlFilter);
		if(times != null){
			String timesStr = times.toString();
			result = Integer.valueOf(timesStr);
		}
		return result;
	}
	
	 
}
